package com.primaryedu.ui.repair;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteTransactionListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.CommonTwoBean;
import com.primaryedu.bean.DepartmentBean;
import com.primaryedu.bean.GoodsTypeBean;
import com.primaryedu.data.Config;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.dialog.PhotosDialog;
import com.primaryedu.photo.PhotoPickerActivity;
import com.primaryedu.photo.PhotoPickerIntent;
import com.primaryedu.photo.PhotoPreviewActivity;
import com.primaryedu.photo.PhotoPreviewIntent;
import com.primaryedu.photo.SelectModel;
import com.primaryedu.picture.PicturePreviewActivity;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.ui.CameraActivity;
import com.primaryedu.utils.ImageUtil;
import com.primaryedu.utils.UploadUtil;
import com.primaryedu.utils.UploadUtil.OnUploadProcessListener;
import com.primaryedu.widget.MyGridView;
import com.primaryedu.widget.pickview.PopDateHelper;

/**
 * 报修-提交
 *
 * @author jun.wang
 * @description
 * @data 2016年12月13日
 */
public class RepairServiceActivity extends BaseActivity implements OnClickListener, OnUploadProcessListener {
    private String TAG = RepairServiceActivity.class.getSimpleName();
    private MyGridView gridView;
    private EditText edit_name, edit_phone, edit_classname;
    private EditText edit_goodsname, edit_content;
    List<CommonTwoBean> list = new ArrayList<>();
    RepairServiceAdapter adapter;
    LayoutInflater inflater;
    private PhotosDialog.Builder Builder;
    Dialog dialog;
    boolean ispreview = true;
    private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果

    /*图片名称 */
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";

    private String imagePath = "";
    private File tempFile;
    private Bitmap bitmap;

    /**
     * 去上传文件
     */
    protected static final int TO_UPLOAD_FILE = 1;
    /**
     * 上传文件响应
     */
    protected static final int UPLOAD_FILE_DONE = 2; //
    protected static final int UPLOAD_VIDEO_DONE = 6; //
    /**
     * 选择文件
     */
    public static final int TO_SELECT_PHOTO = 3;
    /**
     * 上传初始化
     */
    private static final int UPLOAD_INIT_PROCESS = 4;
    /**
     * 上传中
     */
    private static final int UPLOAD_IN_PROCESS = 5;
    /***
     * 这里的这个URL是我服务器的javaEE环境URL
     */
    private static String requestURL = Contants.course_api + "/rest/repair/upload";

    private String picpath1 = "";
    private String picpath2 = "";
    private String picpath3 = "";
    private ArrayList<String> imagePaths = new ArrayList<>();
    private ArrayList<String> paths_show = new ArrayList<>();
    private static final int REQUEST_PHOTO = 1;// 拍照
    private static final int REQUEST_CAMERA_CODE = 10;
    private static final int REQUEST_PREVIEW_CODE = 20;
    private int picIndex = 1;

    private TextView text_department, text_classify;
    PopDateHelper popDateHelper;
    PopDateHelper goodsTypeHelper;
    List<DepartmentBean> departmentList = new ArrayList<>();
    List<GoodsTypeBean> goodsTypeList = new ArrayList<>();
    List<String> strList = new ArrayList<>();
    List<String> strType = new ArrayList<>();
    private RepairServiceAdapter gridAdapter;
    private String video = "";
    private ImageView videoCover;
    private ImageView iv_video_play;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_repair_service);

        init();
    }

    private void init() {
        ((TextView) findViewById(R.id.title)).setText("报修");
        gridView = (MyGridView) this.findViewById(R.id.gridView);

        inflater = LayoutInflater.from(this);

        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.next).setOnClickListener(this);

        edit_name = (EditText) this.findViewById(R.id.edit_name);
        edit_name.setText(GlobalData.getUsername(getApplicationContext()));
        edit_phone = (EditText) this.findViewById(R.id.edit_phone);
        edit_classname = (EditText) this.findViewById(R.id.edit_classname);
        edit_goodsname = (EditText) this.findViewById(R.id.edit_goodsname);
        edit_content = (EditText) this.findViewById(R.id.edit_content);
        text_department = (TextView) this.findViewById(R.id.text_department);
        text_department.setOnClickListener(this);
        text_classify = (TextView) this.findViewById(R.id.text_classify);
        text_classify.setOnClickListener(this);
        videoCover = (ImageView) findViewById(R.id.video_cover);
        iv_video_play = (ImageView) findViewById(R.id.iv_video_play);
        list = new ArrayList<>();

        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gridView.setNumColumns(cols);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("yy", "imagePaths========" + imagePaths.toString());
                String imgs = (String) parent.getItemAtPosition(position);
                if ("paizhao".equals(imgs)) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(RepairServiceActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(1); // 最多选择照片数量，默认为6
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                } else {
//					Toast.makeText(DynamicPublishActivity.this, "1" + position, Toast.LENGTH_SHORT).show();
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(RepairServiceActivity.this);
                    intent.setCurrentItem(position);
                    //如果不加这行会导致选完图片以后在主界面点击图片预览会多出一张没有default_error 的图片
                    imagePaths.remove(imagePaths.size() - 1);

                    intent.setPhotoPaths(imagePaths);
//					intent.setPhotoPathssingle(imagePaths.get(position));
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                }
            }
        });
        imagePaths.add("paizhao");
        gridAdapter = new RepairServiceAdapter(imagePaths);
        gridView.setAdapter(gridAdapter);
//		adapter = new RepairServiceAdapter(this, list) ;
//		gridView.setAdapter(adapter);

//		gridView.setOnItemClickListener(new OnItemClickListener() {
//			@Override
//			public void onItemClick(AdapterView<?> parent, View view,
//					int position, long id) {
//				Intent intent = new Intent(RepairServiceActivity.this, PicturePreviewActivity.class);
//				intent.putExtra("url",list.get(position).getIcon());
//				startActivity(intent);
//			}
//		});

        requestDepartmentData();

        requestGoodsTypeData();
    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_repair_service;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;

            case R.id.next:
                next();
                break;

            case R.id.text_department:
                if (null == strList || strList.size() == 0) {
                    requestDepartmentData();
                } else {
                    popDateHelper.setOnClickOkListener(new PopDateHelper.OnClickOkListener() {
                        @Override
                        public void onClickOk(String date) {
                            text_department.setText(date);
                        }
                    });
                    popDateHelper.show(text_department);
                }
                break;

            case R.id.text_classify:
                if (null == strType || strType.size() == 0) {
                    requestGoodsTypeData();
                } else {
                    goodsTypeHelper.setOnClickOkListener(new PopDateHelper.OnClickOkListener() {
                        @Override
                        public void onClickOk(String date) {
                            text_classify.setText(date);
                        }
                    });
                    goodsTypeHelper.show(text_classify);
                }
                break;
            case R.id.video_cover:
//				playVideo(video);
                intent = new Intent(RepairServiceActivity.this, RepairVideoActivity.class);
                intent.putExtra("video_path", Contants.course_api + picpath_vedio);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void next() {
        if (TextUtils.isEmpty(edit_name.getText().toString())) {
            showToast("请输入您的姓名");
            return;
        }

        if (TextUtils.isEmpty(edit_phone.getText().toString())) {
            showToast("请输入您的手机号");
            return;
        }

        if (TextUtils.isEmpty(edit_classname.getText().toString())) {
            showToast("请输入地点");
            return;
        }

//		if(TextUtils.isEmpty(text_department.getText().toString())){
//			showToast("请选择所在部门");
//			return ;
//		}
//		
//		if(TextUtils.isEmpty(text_classify.getText().toString())){
//			showToast("请选择物品分类");
//			return ;
//		}

        if (TextUtils.isEmpty(edit_goodsname.getText().toString())) {
            showToast("请输入您要报修的物品");
            return;
        }

        if (TextUtils.isEmpty(edit_content.getText().toString())) {
            showToast("请输入您的描述内容");
            return;
        }

//		 三个图片路径
        if (list.size() != 0) {

            if (list.size() == 1) {
                picpath1 = list.get(0).getIcon();
            } else if (list.size() == 2) {
                picpath1 = list.get(0).getIcon();
                picpath2 = list.get(1).getIcon();
            } else if (list.size() == 3) {
                picpath1 = list.get(0).getIcon();
                picpath2 = list.get(1).getIcon();
                picpath3 = list.get(2).getIcon();
            }
        }
//		System.out.println("picpath1=1="+picpath1);
//		System.out.println("picpath=2="+picpath2);
//		System.out.println("picpath1=3="+picpath3);

        requestData();

    }

    private void requestData() {
        showDialog();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.saveRepair,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("saveRepair==" + response);
                        closeDialog();
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            String reason = json.getString("reason");

                            if (result == 1) {
                                showToast(reason);
                                Intent intent = new Intent();
                                setResult(3, intent);
                                finish();
                            } else {
                                showToast(reason);
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                closeDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("userid", GlobalData.getUserId(RepairServiceActivity.this));
                map.put("username", edit_name.getText().toString());
                map.put("tel", edit_phone.getText().toString());
                map.put("classname", edit_classname.getText().toString());
                map.put("goodsname", edit_goodsname.getText().toString());
                map.put("content", edit_content.getText().toString());
                map.put("office", text_department.getText().toString());
                map.put("classify", text_classify.getText().toString());
                map.put("status", "1");   // 默认值 待处理
                map.put("pic1", picpath1);
                map.put("pic2", picpath2);
                map.put("pic3", picpath3);
                map.put("video", picpath_vedio);
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    private static Mode mMode = Mode.NORMAL;

    private enum Mode {
        DEL, NORMAL
    }

    ;

    public class RepairServiceAdapter extends BaseAdapter {

        private ArrayList<String> listUrls;
        private LayoutInflater inflater;

        public RepairServiceAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
            if (listUrls.size() == 7) {
                listUrls.remove(listUrls.size() - 1);
            }
            inflater = LayoutInflater.from(RepairServiceActivity.this);
        }

        public int getCount() {
            return listUrls.size();
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            RepairServiceActivity.RepairServiceAdapter.ViewHolder holder = null;
            if (convertView == null) {
                holder = new RepairServiceActivity.RepairServiceAdapter.ViewHolder();
                convertView = inflater.inflate(R.layout.include_item_published_grida, parent, false);
                holder.image = (ImageView) convertView.findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (RepairServiceActivity.RepairServiceAdapter.ViewHolder) convertView.getTag();
            }

            final String path = listUrls.get(position);
            if (path.equals("paizhao")) {
//				holder.image.setImageResource(R.drawable.icon_addpic_unfocused);
//				holder.image.setOnClickListener(new OnClickListener() {
//					@Override
//					public void onClick(View v) {
//						PhotoPickerIntent intent = new PhotoPickerIntent(RepairServiceActivity.this);
//						intent.setSelectModel(SelectModel.MULTI);
//						intent.setShowCarema(true); // 是否显示拍照
//						intent.setMaxTotal(1); // 最多选择照片数量，默认为6
//						intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
//						startActivityForResult(intent, REQUEST_CAMERA_CODE);
//					}
//				});
                holder.image.setImageResource(R.drawable.icon_addpic_unfocused);
                holder.image.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showPhoto();
                    }
                });
//				showPhoto();
            } else {
                Glide.with(RepairServiceActivity.this)
                        .load(path)
                        .placeholder(R.drawable.default_error)
                        .error(R.drawable.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(holder.image);
            }
            return convertView;
        }

        class ViewHolder {
            ImageView image;
        }
    }

    class RepairServiceYYAdapter extends BaseAdapter {

        private Context context;
        LayoutInflater inflater;
        List<CommonTwoBean> list = new ArrayList<>();
//        LoadImage loadImage;
        protected RequestQueue requestQueue = null;
        private int currentPos = 0;

        public RepairServiceYYAdapter(Context context, List<CommonTwoBean> list) {
            this.context = context;
            this.list = list;
//            loadImage = LoadImage.getInstance();
            inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
            requestQueue = Volley.newRequestQueue(context);
        }

        @Override
        public int getCount() {
            return list.size() + 2;
        }

        @Override
        public Object getItem(int position) {
            if (position >= list.size())
                position = list.size() - 1;
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            //视图循环利用优化
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.item_comment_photo, null);
                holder.icon = (ImageView) convertView.findViewById(R.id.item_icon);
                holder.del = (ImageView) convertView.findViewById(R.id.item_del);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            //加号部分
            if (position == list.size()) {
                holder.icon.setImageResource(R.drawable.icon_jia);
                holder.icon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showPhoto();
                    }
                });
                holder.del.setVisibility(View.GONE);
            } else if (position == list.size() + 1) {//减号部分
                holder.icon.setImageResource(R.drawable.icon_jian);
                holder.icon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mMode == Mode.NORMAL) {
                            mMode = Mode.DEL;
                        } else {
                            mMode = Mode.NORMAL;
                        }
                        refreshUI();
                    }
                });
                holder.del.setVisibility(View.GONE);
            } else {//正常的头像展示部分
                final CommonTwoBean bean = list.get(position);
//                holder.icon.setTag(bean.getIcon());
                Glide.with(context)
                        .load(bean.getIcon())
                        .placeholder(R.drawable.default_error)
                        .error(R.drawable.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(holder.icon);
//                loadImage.addTask(bean.getIcon(), holder.icon);
//                loadImage.doTask();

//				System.out.println("temp_photoaaa"+bean.getIcon());
//				File file = new File(bean.getIcon());
//                if (file.exists()) {
//                	    System.out.println("temp_photobbb"+bean.getIcon());
//                        Bitmap bm = BitmapFactory.decodeFile(bean.getIcon());
//                        //将图片显示到ImageView中
//                        holder.icon.setImageBitmap(bm);
//                }

                holder.icon.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        mMode = Mode.DEL;
                        refreshUI();
                        return true;
                    }
                });

                if (mMode == Mode.NORMAL) {
                    holder.del.setVisibility(View.GONE);
                } else {
                    holder.del.setVisibility(View.VISIBLE);
                }

                holder.del.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        list.remove(position);
                        notifyDataSetChanged();
                    }
                });

                holder.icon.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, PicturePreviewActivity.class);
                        intent.putExtra("url", bean.getIcon());
                        context.startActivity(intent);
                    }
                });
            }

            return convertView;
        }

        public void refreshUI() {
            notifyDataSetChanged();
        }

        private class ViewHolder {
            ImageView icon;
            ImageView del;
        }
    }

    ;

    private void showPhoto() {
        Builder = new PhotosDialog.Builder(RepairServiceActivity.this);
        dialog = Builder.create();
        View view = inflater.inflate(R.layout.dialog_photo, null);

        view.findViewById(R.id.image_take).setOnClickListener(this);
        view.findViewById(R.id.image_video).setOnClickListener(this);

        // 相册
        view.findViewById(R.id.image_video).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
//
//				Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
//				getImage.addCategory(Intent.CATEGORY_OPENABLE);
//				getImage.setType("image/*");
//				startActivityForResult(getImage, PHOTO_REQUEST_GALLERY);
                PhotoPickerIntent intent = new PhotoPickerIntent(RepairServiceActivity.this);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true); // 是否显示拍照
                intent.setMaxTotal(1); // 最多选择照片数量，默认为6
                intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                startActivityForResult(intent, REQUEST_CAMERA_CODE);
            }
        });

        // 拍照
        view.findViewById(R.id.image_take).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
//				Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//				// 判断存储卡是否可以用，可用进行存储
//				if (hasSdcard()) {
//					intent.putExtra(MediaStore.EXTRA_OUTPUT,
//							Uri.fromFile(new File(Environment
//									.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
//				}
//
//				startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
                Intent intent = new Intent(RepairServiceActivity.this, CameraActivity.class);
                startActivityForResult(intent, REQUEST_PHOTO);
            }
        });

        dialog.addContentView(view, new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        dialog.show();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();       //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 1.0);    //宽度设置为屏幕的0.9
        p.height = (int) (d.getHeight() * 0.5);    //宽度设置为屏幕的0.9
        dialog.getWindow().setAttributes(p);     //设置生效
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.setCanceledOnTouchOutside(true);
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
//					Log.d(TAG, "数量："+list.size());
                    loadAdpater(list, false);
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    ispreview = true;
                    ArrayList<String> ListExtra = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
                    loadAdpater(ListExtra, ispreview);
                    break;
            }
        }
        if (requestCode == REQUEST_PHOTO) {
            if (resultCode == 1) {
                try {
                    String picture = data.getStringExtra("picture");
//			ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    ArrayList<String> list = new ArrayList<>();
                    Log.d(TAG, "数量repair：" + list.size());
                    list.add(picture);
                    ispreview = false;
                    loadAdpater(list, ispreview);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    video = data.getStringExtra("video");
                    imagePaths.clear();
                    list.clear();
                    Log.i(TAG, "onActivityResult: repair_video======" + video);
                    gridView.setVisibility(View.GONE);
                    videoCover.setVisibility(View.VISIBLE);
                    iv_video_play.setVisibility(View.VISIBLE);
//					mVideo.setVideoPath(video);
                    videoCover.setOnClickListener(this);
//					mVideo.start();
                    showLoading("加载中...");
                    uploadvideo(video);
//			playVideo(video);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        /*if (requestCode == PHOTO_REQUEST_GALLERY) {
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				crop(uri);
			}

		} else if (requestCode == PHOTO_REQUEST_CAMERA) {
			if (hasSdcard()) {
				tempFile = new File(Environment.getExternalStorageDirectory(),
						PHOTO_FILE_NAME);
				crop(Uri.fromFile(tempFile));

			} else {
				Toast.makeText(RepairServiceActivity.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_LONG)
						.show();
			}

		} else if (requestCode == PHOTO_REQUEST_CUT) {
			try {
				bitmap = data.getParcelableExtra("data");
//				this.headImage.setImageBitmap(bitmap);
				// 删除临时文件
				ImageUtil.saveToSdcard(bitmap);
				imagePath = Config.SDPATH_HEAD + "temp_photo.jpg";

				// 替换服务器上面的头像
//				toUploadFile() ;
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}*/

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void loadAdpater(ArrayList<String> paths, boolean ispreview) {

        if (ispreview) {
            imagePaths.clear();
            imagePaths.addAll(paths);
            if (imagePaths.contains("paizhao")) {
                imagePaths.remove("paizhao");
                imagePaths.add("paizhao");
            } else {
                imagePaths.add("paizhao");
            }
            Log.i("yy", "loadAdpater: paths.size======" + paths.size());
            Log.i("yy", "loadAdpater: paths.size======" + paths.toString());
//			Log.i("yy", "loadAdpater: paths.get(2)===== "+ paths.get(2));
            gridAdapter = new RepairServiceAdapter(imagePaths);
            gridView.setAdapter(gridAdapter);
            list.clear();
            for (int i = 0; i < paths.size(); i++) {
                String result = paths.get(i).toString().substring(webServerUrl.length());
                Log.i("yy", "result==" + result);
                CommonTwoBean bean = new CommonTwoBean();
                bean.setIcon(result);
                list.add(bean);
            }

            Log.i("yy", "list.size======" + list.toString());
        } else {
            if (imagePaths != null && imagePaths.size() > 0) {
                imagePaths.remove("paizhao");
            }
            if (paths.contains("paizhao")) {
                paths.remove("paizhao");
            }
            if (imagePaths.size() > 2) {
                showToast("报修最多选择三张图片！");
                imagePaths.add("paizhao");
            } else {
                showLoading("加载中...");
                String imagepath = ImageUtil.compressImage(paths.get(0), Config.SDPATH_HEAD + "temp_photo.jpg", 30);
                toUploadFile(imagepath);
            }
        }
//		paths.add("paizhao");
//		imagePaths.addAll(paths);
        Log.i("yy", "loadAdpater: imagePaths=====" + imagePaths.toString());

//		for (int i = 0; i < imagePaths.size(); i++) {
//			if (imagePaths.contains("paizhao")){
//				imagePaths.remove("paizhao");
//			}
//			toUploadFile(imagePaths.get(i));
//		}
		/*if(imagePaths.size() != 0){
			 if(imagePaths.size() == 1){
				  picpath1 = imagePaths.get(0) ;
				 Log.i("yy", "loadAdpater: picpath1====" + picpath1);
			 }else if (imagePaths.size() == 2) {
				 picpath1 = imagePaths.get(0);
				 picpath2 = imagePaths.get(1) ;
				 Log.i("yy", "loadAdpater: picpath1====" + picpath1);
				 Log.i("yy", "loadAdpater: picpath2====" + picpath2);
			 }else if (imagePaths.size() == 3) {
				 picpath1 = imagePaths.get(0) ;
				 picpath2 = imagePaths.get(1) ;
				 picpath3 = imagePaths.get(2) ;
				 Log.i("yy", "loadAdpater: picpath1====" + picpath1);
				 Log.i("yy", "loadAdpater: picpath2====" + picpath2);
				 Log.i("yy", "loadAdpater: picpath3====" + picpath3);
			 }
		}
//		if (imagePaths.size() <= 4) {
            gridAdapter = new RepairServiceAdapter(imagePaths);
            gridView.setAdapter(gridAdapter);*/
//        }else {
//			showToast("报修图片最多放三张！");
//			Log.i("yy", "loadAdpater: imagePathsremove=====" +imagePaths.toString());
//		}
        try {
            JSONArray obj = new JSONArray(imagePaths);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 剪切图片
     *
     * @param uri
     * @function:
     * @author:Jerry
     * @date:2015-04-15
     */
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    private void toUploadFile(String imagepath) {
        String fileKey = "pic1";   // 服务器与客户端协调好的key值或叫name值
        UploadUtil uploadUtil = UploadUtil.getInstance();
        uploadUtil.setOnUploadProcessListener(this); // 设置监听器监听上传状态

        System.out.println("temp_photo==" + Config.SDPATH_HEAD + "temp_photo.jpg");
        uploadUtil.uploadFile(imagepath, fileKey,
                requestURL, null);
    }

    private void uploadvideo(String video) {
        String fileKey = "video";   // 服务器与客户端协调好的key值或叫name值
        UploadUtil uploadUtil = UploadUtil.getInstance();
        uploadUtil.setOnUploadProcessListener(this); // 设置监听器监听上传状态

//		Map<String, String> params = new HashMap<String, String>();
//		params.put("userid",GlobalData.accountBean.getId());
        String requestURL = Contants.course_api + "/rest/upload/video";
        uploadUtil.uploadFile(video, fileKey,
                requestURL, null);
    }

    @Override
    public void onUploadDone(int responseCode, String message) {
        Message msg = Message.obtain();
        if (video != "") {
            msg.what = UPLOAD_VIDEO_DONE;
        } else {
            msg.what = UPLOAD_FILE_DONE;
        }
        msg.arg1 = responseCode;
        msg.obj = message;
        handler.sendMessage(msg);
    }

    @Override
    public void onUploadProcess(int uploadSize) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_IN_PROCESS;
        msg.arg1 = uploadSize;
        handler.sendMessage(msg);
    }

    @Override
    public void initUpload(int fileSize) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_INIT_PROCESS;
        msg.arg1 = fileSize;
        handler.sendMessage(msg);
    }

    private String pic_path;
    private String picpath_vedio = "";
    private String video_path = "";
    private String webServerUrl;
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
//				setData() ;
                    break;

                case UPLOAD_FILE_DONE:
                    dismissLoading();
                    String jsonStr = msg.obj.toString();
                    System.out.println("json_repair===" + jsonStr);

                    try {
                        JSONObject json = new JSONObject(jsonStr);
                        int result = json.getInt("result");
                        String reason = json.getString("reason");
                        if (result == 1) {
                            String data = json.getString("data");
                            JSONObject listObj = new JSONObject(data);
                            pic_path = listObj.getString("picpath1");
                            Log.i("yy", "pic_path======" + pic_path);
                            webServerUrl = listObj.getString("webServerUrl");
                            Log.i("yy", "webServerUrl======" + webServerUrl);
                            Log.i("yy", "length======" + webServerUrl.length());

                            imagePaths.add(webServerUrl + pic_path);
                            if (imagePaths.contains("paizhao")) {
                                imagePaths.remove("paizhao");
                                imagePaths.add("paizhao");
                            } else {
                                imagePaths.add("paizhao");
                            }
                            if (!TextUtils.isEmpty(pic_path)) {
                                CommonTwoBean bean = new CommonTwoBean();
                                bean.setIcon(pic_path);
                                list.add(bean);
                            }

                            if (null != imagePaths && imagePaths.size() != 0) {
                                gridAdapter = new RepairServiceAdapter(imagePaths);
                                gridView.setAdapter(gridAdapter);
                            }
                            System.out.println("list====" + list.toString());
                        } else {
                            showToast(reason);
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case UPLOAD_VIDEO_DONE:
                    dismissLoading();
                    String jsonString = msg.obj.toString();
                    System.out.println("json_repair_video===" + jsonString);

                    try {
                        JSONObject json = new JSONObject(jsonString);
                        int result = json.getInt("result");
                        String reason = json.getString("reason");

                        if (result == 1) {
                            String data = json.getString("data");
                            Log.i("yy", "handleMessage: data" + data);
                            JSONObject listObj = new JSONObject(data);
                            picpath_vedio = listObj.getString("picpath1");
                            String webServerUrl = listObj.getString("webServerUrl");
                            video_path = webServerUrl + picpath_vedio;
//							JSONArray listarray = new JSONArray(data);
//							String pic = listarray.getString(0);
                            Log.i("yy", "handleMessage: repair_video_path========" + video_path);
//							String webServerUrl = listObj.getString("webServerUrl") ;
//							mVideo.setVideoPath(video_path);
//							mVideo.start();
//							if(!TextUtils.isEmpty(video_path)){
//								Releasethedynamic();
//							}

                            MediaMetadataRetriever media = new MediaMetadataRetriever();

                            media.setDataSource(video_path, new HashMap<String, String>());
                            Bitmap frameAtTime = media.getFrameAtTime();
                            videoCover.setImageBitmap(frameAtTime);


                        } else {
                            showToast(reason);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                case 1002:
                    popDateHelper = new PopDateHelper(RepairServiceActivity.this, strList);
                    break;

                case 1003:
                    goodsTypeHelper = new PopDateHelper(RepairServiceActivity.this, strType);
                    break;

                default:
                    break;
            }
        }

        ;
    };

    // 部门数据
    private void requestDepartmentData() {
        StringBuilder builder = new StringBuilder();
        builder.append(Contants.getSelect);

        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                builder.toString(), new Response.Listener<String>() {

            @Override
            public void onResponse(String arg0) {
                try {
                    System.out.println("getSelect===" + arg0.toString());
                    JSONObject json = new JSONObject(arg0);
                    String reason = json.getString("reason");
                    int result = json.getInt("result");
                    String data = json.getString("data");
                    if (result == 1) {
                        departmentList = new Gson().fromJson(data,
                                new TypeToken<List<DepartmentBean>>() {
                                }.getType());

                        strList.clear();
                        if (null != departmentList && departmentList.size() != 0) {
                            for (int i = 0; i < departmentList.size(); i++) {
                                strList.add(departmentList.get(i).getName());
                            }
                        }
                        System.out.println("departmentList==" + strList);
                        handler.sendEmptyMessage(1002);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
//	            showToast(ErrorMsg.net_error) ;
            }
        });
        //为此get请求设置一个Tag属性
        stringRequest.setTag("GET_TAG");
        //将此get请求加入
        requestQueue.add(stringRequest);
    }

    // 部分类别
    private void requestGoodsTypeData() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.getPageListJson,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("getPageListJson==" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

                                goodsTypeList = new Gson().fromJson(listStr,
                                        new TypeToken<List<GoodsTypeBean>>() {
                                        }.getType());

                                strType.clear();
                                if (null != goodsTypeList && goodsTypeList.size() != 0) {

                                    for (int i = 0; i < goodsTypeList.size(); i++) {
                                        strType.add(goodsTypeList.get(i).getLabel());
                                    }
                                }
                                handler.sendEmptyMessage(1003);
                                System.out.println("goodsTypeList==" + goodsTypeList);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("type", "classify");
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }
}
